const { Controller } = require("egg");

class ApiWxmsgdbController extends Controller {
  async showMsg() {
    const { ctx } = this;
    const wxid = ctx.request.body.selectedWxid;
    const fromWxid = ctx.request.body.friendwxid;
    const page = parseInt(ctx.request.body.page) || 1;
    const pageSize = parseInt(ctx.request.body.pageSize) || 20;
    // console.log(ctx.request.body)
    // 参数验证
    if (!fromWxid || !wxid) {
      ctx.body = {
        code: 40000,
        msg: "缺少必要参数",
      };
      return;
    }

    try {
      // 先获取所有消息并排序
      const [Wxmsgdbs, sendMsgs] = await Promise.all([
        ctx.model.Wxmsgdb.find({
          "data.fromWxid": fromWxid,
          wxid,
        }).sort({ timestamp: -1 }),

        ctx.model.Sendmsg.find({
          fromWxid,
          wxid,
        }).sort({ timestamp: -1 }),
      ]);

      // 合并所有消息并按时间戳排序
      const allMessages = [...Wxmsgdbs, ...sendMsgs].sort(
        (a, b) => b.timestamp - a.timestamp
      );

      // 计算分页
      const totalCount = allMessages.length;
      const totalPages = Math.ceil(totalCount / pageSize);
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;

      // 截取当前页的消息
      const pageMessages = allMessages
        .slice(startIndex, endIndex)
        .map((msg) => {
          const isSendMsg = msg.collection?.modelName === "Sendmsg";

          if (isSendMsg) {
            return {
              ownerWxid: wxid,
              id: msg._id,
              fromWxid: msg.fromWxid,
              fromNick: msg.fromNick,
              content: msg.msg,
              msgType: msg.msgtype,
              timestamp: msg.timestamp,
              date: msg.date,
              msgId: msg.msgId,
              sendId: msg.sendId,
              tags: msg.tags || [],
              direction: "send",
            };
          } else {
            return {
              ownerWxid: msg.wxid,
              id: msg._id,
              fromWxid: msg.data.fromWxid,
              content: msg.data.msg,
              msgType: msg.data.msgType,
              fromType: msg.data.fromType,
              timestamp: msg.timestamp,
              date: msg.date,
              msgId: msg.data.msgId,
              sendId: msg.data.sendId,
              tags: msg.tags || [],
              ai: msg.ai || {},
              direction: "receive",
            };
          }
        });

      ctx.body = {
        code: 20000,
        msg: "获取消息列表成功",
        data: {
          messages: pageMessages,
          pagination: {
            currentPage: page,
            pageSize,
            totalPages,
            total: totalCount,
          },
        },
      };
    } catch (error) {
      ctx.logger.error("获取消息记录失败:", error);
      ctx.body = {
        code: 50000,
        msg: error.message || "获取消息记录失败",
        data: {
          messages: [],
          pagination: {
            currentPage: page,
            pageSize,
            totalPages: 0,
            total: 0,
          },
        },
      };
    }
  }

  async showRoomMsg() {
    const { ctx } = this;
    const mywxid = ctx.request.body.selectedWxid;
    const fromWxid = ctx.request.body.groupwxid;
    const page = parseInt(ctx.request.body.page);
    const pageSize = parseInt(ctx.request.body.pageSize);
    const field = ctx.request.body.field || {};

    // 参数验证
    if (!fromWxid || !mywxid) {
      ctx.body = {
        code: 40000,
        msg: "缺少必要参数",
      };
      return;
    }

    // 构建查询条件
    let query = { "data.fromWxid": fromWxid };

    if (field.msg) {
      query["data.msg"] = new RegExp(field.msg, "i");
    }

    try {
      // 获取总记录数
      const totalCount = await ctx.model.Wxchatroomdb.countDocuments(query);

      // 计算总页数
      const totalPages = Math.ceil(totalCount / pageSize);
      const startIndex = (page - 1) * pageSize;

      // 分页查询
      const messages = await ctx.model.Wxchatroomdb.find(query)
        .sort({ timestamp: -1 })
        .skip(startIndex)
        .limit(pageSize);

      // 格式化消息
      const pageMessages = messages.map((msg) => ({
        ownerWxid: msg.wxid,
        id: msg._id,
        fromWxid: msg.data.fromWxid,
        content: msg.data.msg,
        msgType: msg.data.msgType,
        fromType: msg.data.fromType,
        timestamp: msg.timestamp,
        date: msg.date,
        msgId: msg.data.msgId,
        sendId: msg.data.sendId,
        tags: msg.tags || [],
        ai: msg.ai || {},
        direction: "receive",
      }));

      ctx.body = {
        code: 20000,
        msg: "获取聊天室消息成功",
        data: {
          messages: pageMessages,
          pagination: {
            currentPage: page,
            pageSize,
            totalPages,
            total: totalCount,
          },
        },
      };
    } catch (error) {
      ctx.logger.error("获取聊天室消息失败:", error);
      ctx.body = {
        code: 50000,
        msg: error.message || "获取聊天室消息失败",
        data: {
          messages: [],
          pagination: {
            currentPage: page,
            pageSize,
            totalPages: 0,
            total: 0,
          },
        },
      };
    }
  }

  async groupmsgdelete() {
    const { ctx } = this;
    const mywxid = ctx.request.body.selectedWxid;
    const fromWxid = ctx.request.body.groupwxid;

    // 参数验证
    if (!fromWxid || !mywxid) {
      ctx.body = {
        code: 40000,
        msg: "缺少必要参数",
      };
      return;
    }

    try {
      // 删除群聊消息记录
      const result = await ctx.model.Wxchatroomdb.deleteMany({
        "data.fromWxid": fromWxid,
        wxid: mywxid,
      });

      ctx.body = {
        code: 20000,
        msg: "删除聊天记录成功",
        data: {
          deletedCount: result.deletedCount,
        },
      };
    } catch (error) {
      ctx.logger.error("删除聊天记录失败:", error);
      ctx.body = {
        code: 50000,
        msg: error.message || "删除聊天记录失败",
        data: {
          deletedCount: 0,
        },
      };
    }
  }

  async friendmsgdelete() {
    const { ctx } = this;
    const mywxid = ctx.request.body.selectedWxid;
    const fromWxid = ctx.request.body.friendwxid;

    // 参数验证
    if (!fromWxid || !mywxid) {
      ctx.body = {
        code: 40000,
        msg: "缺少必要参数",
      };
      return;
    }

    try {
      // 删除消息记录
      const result = await ctx.model.Wxmsgdb.deleteMany({
        "data.fromWxid": fromWxid,
        wxid: mywxid,
      });
      if (result.deletedCount > 0) {
        await ctx.service.wxfriend.editFriend(mywxid, fromWxid, {
          ischat: false,
        });
      }
      ctx.body = {
        code: 20000,
        msg: "删除聊天记录成功",
        data: {
          deletedCount: result.deletedCount,
        },
      };
    } catch (error) {
      ctx.logger.error("删除聊天记录失败:", error);
      ctx.body = {
        code: 50000,
        msg: error.message || "删除聊天记录失败",
        data: {
          deletedCount: 0,
        },
      };
    }
  }

  async createForward() {
    const { ctx } = this;
    const { ownerWxid, tolist, fromlist } = ctx.request.body;
  
    // 参数验证
    if (!ownerWxid || !Array.isArray(tolist) || !Array.isArray(fromlist)) {
      ctx.body = {
        code: 40000,
        msg: "参数错误：ownerWxid、tolist 和 fromlist 是必填项且必须为数组",
      };
      return;
    }
  
    const created = [];
  
    try {
      // 日志记录开始
      ctx.logger.info(`开始创建转发规则，ownerWxid: ${ownerWxid}, fromlist: ${JSON.stringify(fromlist)}, tolist: ${JSON.stringify(tolist)}`);
  
      // 遍历 fromlist 和 tolist 的笛卡尔积组合
      for (const fromwxid of fromlist) {
        const res2 = await ctx.service.getinfo.queryObj(fromwxid, ownerWxid);
        if (!res2) {
          ctx.logger.warn(`无法获取来源用户信息，fromwxid: ${fromwxid}`);
          continue; // 跳过无效的 fromwxid
        }
  
        for (const wxid of tolist) {
          const res1 = await ctx.service.getinfo.queryObj(wxid, ownerWxid);
          if (!res1) {
            ctx.logger.warn(`无法获取目标用户信息，wxid: ${wxid}`);
            continue; // 跳过无效的 wxid
          }
  
          // 创建 Forward 记录
          const forward = await ctx.model.Forward.create({
            ownerWxid,
            wxid,
            nick: res1.result.nick,
            fromwxid,
            fromnick: res2.result.nick,
          });
  
          created.push(forward);
          ctx.logger.info(`成功创建转发规则: ${fromwxid} -> ${wxid}`);
        }
      }
  
      if (created.length > 0) {
        ctx.body = {
          code: 20000,
          msg: "创建成功",
          data: created,
        };
      } else {
        ctx.body = {
          code: 50000,
          msg: "未创建任何转发规则，请检查输入数据",
        };
      }
    } catch (error) {
      ctx.logger.error("创建转发规则失败:", error.message);
      ctx.body = {
        code: 50000,
        msg: "请求失败，请检查网络或接口状态",
      };
    }
  }

  async getForward() {
    const { ctx } = this;
    const { ownerWxid, field, page = 1, pageSize = 20 } = ctx.request.body;

    // 参数验证
    if (!ownerWxid) {
      ctx.body = {
        code: 40000,
        msg: "缺少必要参数：ownerWxid",
      };
      return;
    }

    try {
      let query = { ownerWxid };

      // 构建查询条件
      if (field?.wxid) {
        query.wxid = new RegExp(field.wxid, "i");
      }
      if (field?.fromwxid) {
        query.fromwxid = new RegExp(field.fromwxid, "i");
      }
      if (typeof field?.status !== "undefined") {
        query.status = field.status;
      }

      // 获取总数
      const total = await ctx.model.Forward.countDocuments(query);

      // 分页查询
      const list = await ctx.model.Forward.find(query)
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .sort({ createdAt: -1 });

      ctx.body = {
        code: 20000,
        msg: "查询成功",
        data: {
          list,
          count: total,
        },
      };
    } catch (error) {
      ctx.logger.error("查询失败:", error.message);
      ctx.body = {
        code: 50000,
        msg: "请求失败，请检查网络或接口状态",
      };
    }
  }

  async deleteForward() {
    const { ctx } = this;
    const { ids } = ctx.request.body;

    // 参数验证
    if (!Array.isArray(ids) || ids.length === 0) {
      ctx.body = {
        code: 40000,
        msg: "缺少有效的删除ID列表",
      };
      return;
    }

    try {
      const result = await ctx.model.Forward.deleteMany({
        _id: { $in: ids },
      });

      ctx.body = {
        code: 20000,
        msg: "删除成功",
        data: {
          deletedCount: result.deletedCount,
        },
      };
    } catch (error) {
      ctx.logger.error("删除失败:", error.message);
      ctx.body = {
        code: 50000,
        msg: "请求失败，请检查网络或接口状态",
      };
    }
  }

  async updateForward() {
    const { ctx } = this;
    const { ids, updateData } = ctx.request.body;

    // 参数验证
    if (!Array.isArray(ids) || ids.length === 0) {
      ctx.body = {
        code: 40000,
        msg: "缺少有效的更新ID列表",
      };
      return;
    }

    if (!updateData || typeof updateData !== "object") {
      ctx.body = {
        code: 40000,
        msg: "缺少有效的更新数据",
      };
      return;
    }

    try {
      const result = await ctx.model.Forward.updateMany(
        { _id: { $in: ids } },
        { $set: updateData }
      );

      ctx.body = {
        code: 20000,
        msg: "更新成功",
        data: {
          matchedCount: result.matchedCount,
          modifiedCount: result.modifiedCount,
        },
      };
    } catch (error) {
      ctx.logger.error("更新失败:", error.message);
      ctx.body = {
        code: 50000,
        msg: "请求失败，请检查网络或接口状态",
      };
    }
  }
}

module.exports = ApiWxmsgdbController;
